<?php

namespace Biz\model\theParagraph;

use Biz\service\Goods;


class CollocationGoods extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_the_paragraph';

    const _DATABASE_ = 'the_paragraph';

    const _TABLE_NAME = 'collocation_goods';


    const STATUS_NORMAL = 1;
    const STATUS_DELETE = 9;


    public static function addCollocationGoods($storeId, $roomId, $collocationId, $goodsSkuInfos)
    {
        foreach ($goodsSkuInfos as $goodsId => $skuInfo) {
            $data = [
                'store_id' => $storeId,
                'room_id' => $roomId,
                'collocation_id' => $collocationId,
                'goods_id' => $goodsId,
                'status' => self::STATUS_NORMAL,
                'sku_id' => $skuInfo[0]['sku_id'],
                'addtime' => date('Y-m-d H:i:s')
            ];
            self::insert($data);
        }
        return true;
    }

    public static function updateCollocationGoods($goodsId, $data)
    {
        $ret = self::update($data, ['id' => $goodsId]);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function saveCollocationGoodsSort($sortInfo)
    {
        foreach ($sortInfo as $goodsId => $sort) {
            self::update(['sort' => $sort], ['id' => $goodsId]);
        }
    }

    public static function getCollocationIdsByGoodsId($goodsId)
    {
        return self::select("collocation_id", [
            'goods_id' => $goodsId,
            'status' => self::STATUS_NORMAL
        ]);
    }

    public static function getGoodsByCollocationId($collocationId, $withGoodsInfo = true)
    {
        $CollocationGoods = self::select("*",
            [
                'AND' => [
                    'collocation_id' => $collocationId,
                    'status' => self::STATUS_NORMAL
                ],
                'ORDER' => [
                    'sort',
                    'id'
                ]
            ]);
        if($withGoodsInfo){
            return self::formatGoods($CollocationGoods);
        }else{
            return $CollocationGoods;
        }

    }

    private static function formatGoods($collocationGoods)
    {
        $goodsIds = array_column($collocationGoods, 'goods_id');
        $goodsInfos = Goods::Goods($goodsIds);
        foreach ($collocationGoods as &$goods) {
            if (isset($goodsInfos[$goods['goods_id']])) {
                $goods['goods_info'] = $goodsInfos[$goods['goods_id']];
            }
        }
        return $collocationGoods;
    }

    public static function changeGoodsStatusById($id, $status)
    {
        if (self::update(['status' => $status], ["id" => $id])->rowcount()) {
            return $id;
        }
    }

    public static function setGoodsSkuId($id, $skuId)
    {
        if (self::update(['sku_id' => $skuId], ["id" => $id])->rowcount()) {
            return $id;
        }
    }
}